<?php
/*
 * GNU Social - a federating social network
 * Copyright (C) 2014, Free Software Foundation, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

if (!defined('GNUSOCIAL')) { exit(1); }

/**
 * @package     Plugin
 * @maintainer  kim <kim@surtdelcercle.cat>
 */
class NoGafamPlugin extends Plugin
{
  const PLUGIN_VERSION = '1.0.0';

  static function settings($setting)
  {
  	// Invidious instance
  	$settings['invidious'] = 'https://invidio.us';
  	// Nitter url
  	$settings['nitter']    = 'https://nitter.net';

  	// config.php settings override the settings in this file
  	$configsettings = common_config('site','gafam') ?: array();
  	foreach($configsettings as $configsetting => $value) {
  		$settings[$configsetting] = $value;
  	}

  	if(isset($settings[$setting])) {
  		return $settings[$setting];
  	}
  	else {
  		return false;
  	}
  }

  public function initialize()
  {
      return true;
  }

  /**
   * Hook notice save
   *
   * @param Notice &$notice Notice being saved
   *
   * @return boolean hook value
   */
  function onStartNoticeSaveWeb(Action $action, Profile $author, &$content, &$options)
  {
       $content = $this->checkGafamUrls($content);
       return true;
  }

  function checkGafamUrls($content)
  {
    $invidious = static::settings('invidious');
    $nitter    = static::settings('nitter');

    //possible youtube urls
    $content = str_replace('https://youtube.com', $invidious, $content);
    $content = str_replace('https://www.youtube.com', $invidious, $content);
    $content = str_replace('https://m.youtube.com', $invidious, $content);

    //possible twitter urls
    $content = str_replace('https://twitter.com', $nitter, $content);
    $content = str_replace('https://www.twitter.com', $nitter, $content);
    $content = str_replace('https://mobile.twitter.com', $nitter, $content);
    $content = str_replace('https://t.co', $nitter, $content);

    return $content;
  }

  public function onPluginVersion(array &$versions)
  {
      $versions[] = array('name' => 'NoGafam',
        'version' => self::PLUGIN_VERSION,
        'author' => 'Kim',
        'homepage' => 'https://social.surtdelcercle.cat',
        'rawdescription' =>
        // TRANS: Plugin description.
        _m('A simple script to replace GAFAM urls.'));

      return true;
  }
}
